package com.yhk.wuchat.common.user.service.adapter;

import cn.hutool.core.bean.BeanUtil;
import com.yhk.wuchat.common.common.domain.enums.YesOrNoEnum;
import com.yhk.wuchat.common.user.domain.entity.ItemConfig;
import com.yhk.wuchat.common.user.domain.entity.User;
import com.yhk.wuchat.common.user.domain.entity.UserBackpack;
import com.yhk.wuchat.common.user.domain.vo.resp.BadgeResp;
import com.yhk.wuchat.common.user.domain.vo.resp.UserInfoResp;
import me.chanjar.weixin.common.bean.WxOAuth2UserInfo;

import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @version 1.0
 * @Author moresuo
 * @Date 2024/4/3 18:00
 * @注释 用户适配器
 */
public class UserAdapter {

    public static User buildUsersave(String fromUser) {
        return User.builder().openId(fromUser).build();
    }

    /**
     * 补全用户信息，微信登录的信息
     * @param id
     * @param userInfo
     * @return
     */
    public static User buildAuthorizeUser(Long id, WxOAuth2UserInfo userInfo) {
        User user=new User();
        user.setId(id);
        user.setName(userInfo.getNickname());
        user.setAvatar(userInfo.getHeadImgUrl());
        return user;
    }

    /**
     * 补全用户信息，改名次数信息
     * @param user
     * @param modifyNameCount
     * @return
     */
    public static UserInfoResp buildUserInfo(User user, Integer modifyNameCount) {
        UserInfoResp resp=new UserInfoResp();
        BeanUtil.copyProperties(user, resp);
        resp.setId(user.getId());
        resp.setModifyNameChance(modifyNameCount);
        return resp;
    }

    /**
     * 构建用户的徽章信息
     * @param itemConfigs
     * @param backpacks
     * @param user
     * @return
     */
    public static List<BadgeResp> buildBadgeResp(List<ItemConfig> itemConfigs, List<UserBackpack> backpacks, User user) {
        Set<Long> obtainItemSet = backpacks.stream().map(UserBackpack::getItemId).collect(Collectors.toSet());
        return itemConfigs.stream().map(x->{
            BadgeResp badgeResp=new BadgeResp();
            BeanUtil.copyProperties(x,badgeResp);
            badgeResp.setObtain(obtainItemSet.contains(x.getId())? YesOrNoEnum.YES.getStatus() : YesOrNoEnum.NO.getStatus());
            badgeResp.setWearing(Objects.equals(x.getId(), user.getItemId())? YesOrNoEnum.YES.getStatus() : YesOrNoEnum.NO.getStatus());
            return badgeResp;
        }).sorted(Comparator.comparing(BadgeResp::getWearing,Comparator.reverseOrder()
                ).thenComparing(BadgeResp::getObtain,Comparator.reverseOrder()))
                .collect(Collectors.toList());
    }
}
